<template>
    <div class="order_manage_container">
        <ZWSearch
            row-num="3"
            :option="searchOption"
            @search="search"
            @reset="reset"
            @input="changeSearchForm"
            @expand="expandSearch" />
        <ZWTable
            ref="orderTableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            @dataChange="tableDataChange">
            <template #headerOperateLeft>
                <div style="display: flex; align-items: center">
                    <div style="font-size: 13px; line-height: 1; margin-right: 10px">
                        最近同步时间：{{ updateTime }}
                    </div>
                    <div style="display: flex; align-items: center">
                        <el-dropdown style="margin-left: 10px">
                            <span
                                style="
                                    color: #ff6b00;
                                    font-size: 12px;
                                    cursor: pointer;
                                    line-height: 1;
                                    padding-right: 6px;
                                ">
                                同步订单<el-icon class="el-icon--right"><arrow-down /></el-icon>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item @click="synchronousData">
                                        直接同步&nbsp;
                                        <el-tooltip class="box-item" effect="dark" placement="top">
                                            <template #content>
                                                <div style="max-width: 260px; margin-bottom: -6px">
                                                    <p
                                                        v-for="item in synchronousTips"
                                                        :key="item.id"
                                                        style="font-size: 12px; line-height: 1.6; margin-bottom: 6px">
                                                        {{ item.text }}
                                                    </p>
                                                </div>
                                            </template>
                                            <el-image class="question-icon" src="/static/question.png"></el-image>
                                        </el-tooltip>
                                    </el-dropdown-item>
                                    <el-dropdown-item @click="synchronousProData">
                                        高级同步&nbsp;
                                        <el-tooltip
                                            class="box-item"
                                            effect="dark"
                                            :content="synchronousProTips"
                                            placement="top">
                                            <el-image class="question-icon" src="/static/question.png"></el-image>
                                        </el-tooltip>
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                        <el-tooltip
                            class="box-item"
                            effect="dark"
                            :content="synchronousOrderTips"
                            placement="right-start">
                            <el-image src="/static/question.png" style="width: 16px; height: 16px"></el-image>
                        </el-tooltip>
                    </div>
                    <div
                        v-if="isShowRefresh"
                        style="font-size: 13px; line-height: 1; margin-left: 10px; cursor: pointer; color: #ff6b00"
                        @click="reloadTable">
                        刷新
                    </div>
                    <div
                        v-if="isShowRefreshExport"
                        style="font-size: 13px; line-height: 1; margin-left: 10px; cursor: pointer; color: #ff6b00"
                        @click="resetExport">
                        刷新导入订单
                    </div>
                </div>
            </template>
            <template #headerOperate>
                <!-- 国栋说的先隐藏掉 -->
                <!-- <el-button @click="exportOrdersClick">导出订单</el-button> -->
                <!-- 20230815 导入订单隐藏 -->
                <!-- <el-button type="primary" @click="importOrdersClick">导入订单</el-button> -->
            </template>
        </ZWTable>
    </div>

    <!-- 高级同步 -->
    <Dialog :app-dialog="appDialogSynchronousPro">
        <el-form
            ref="synchronousProFormRef"
            :model="synchronousProForm"
            :rules="synchronousProFormRules"
            label-width="auto">
            <el-form-item label="归属店铺" prop="shop_id">
                <select-store v-model="synchronousProForm.shop_id" :is-disabled-line="true" @change="changeStore" />
            </el-form-item>
            <el-form-item label="下单时间" prop="order_time">
                <el-date-picker
                    v-model="synchronousProForm.order_time"
                    :editable="false"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="daterange"
                    range-separator="—"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    prefix-icon="Calendar"
                    size="small"
                    :disabled-date="disabledDate"
                    @calendar-change="handleChange"
                    @focus="handleFocus" />
                <div v-show="!douTips" style="font-size: 12px">最多选择{{ impose }}天的数据</div>
                <div v-show="douTips" style="font-size: 12px">
                    因平台限制，仅支持同步最近90天以内（不包括90天）的订单数据
                </div>
            </el-form-item>
            <el-form-item label="订单处理" prop="method">
                <div style="font-size: 13px">订单编号相同时，请选择以下处理方式</div>
                <el-radio-group v-model="synchronousProForm.method" class="holiday_box">
                    <el-radio class="holiday_item" :label="1" :value="1">
                        跳过订单
                        <el-tooltip class="box-item" effect="light" placement="top">
                            <template #content>
                                <div style="max-width: 260px; margin-bottom: -6px">
                                    <p style="color: #666; font-size: 12px; line-height: 1.6; margin-bottom: 6px">
                                        订单编号相同时，不再导入系统。
                                    </p>
                                </div>
                            </template>
                            <el-image class="question-icon" src="/static/question.png"></el-image>
                        </el-tooltip>
                    </el-radio>
                    <el-radio class="holiday_item" :label="2" :value="2">
                        更新订单
                        <el-tooltip class="box-item" effect="light" placement="top">
                            <template #content>
                                <div style="max-width: 260px; margin-bottom: -6px">
                                    <p style="color: #666; font-size: 12px; line-height: 1.6; margin-bottom: 6px">
                                        订单编号相同时，将会更新至系统。
                                    </p>
                                </div>
                            </template>
                            <el-image class="question-icon" src="/static/question.png"></el-image>
                        </el-tooltip>
                    </el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
    </Dialog>
    <!-- 导入订单 -->
    <Dialog :app-dialog="appDialogImportOrders">
        <el-form ref="importOrdersFormRef" :model="importOrdersForm" :rules="importOrdersFormRules" label-width="auto">
            <el-form-item label="选择店铺" prop="shop_id">
                <el-select v-model="importOrdersForm.shop_id" placeholder="请选择店铺" @change="changeShop">
                    <el-option
                        v-for="item in orderStoreTypes"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                        :disabled="item.is_open == 1">
                        <div style="display: flex; align-items: center">
                            <el-image class="shop-icon" :src="item.shop_icon" fit="fill"></el-image>
                            <div>{{ item.name }}</div>
                        </div>
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="订单信息">
                <div>{{ tips }}</div>
                <el-radio-group v-model="importOrdersForm.method">
                    <el-radio :label="1" size="large">
                        跳过订单
                        <el-tooltip class="box-item" placement="top">
                            <template #content>
                                <div style="max-width: 260px; margin-bottom: -6px">
                                    <p style="font-size: 12px; line-height: 1.6; margin-bottom: 6px">
                                        订单编号相同时，不再导入系统。
                                    </p>
                                </div>
                            </template>
                            <el-image class="question-icon" src="/static/question.png"></el-image>
                        </el-tooltip>
                    </el-radio>
                    <el-radio :label="2" size="large">
                        更新订单
                        <el-tooltip class="box-item" placement="top">
                            <template #content>
                                <div style="max-width: 260px; margin-bottom: -6px">
                                    <p style="font-size: 12px; line-height: 1.6; margin-bottom: 6px">
                                        订单编号相同时，将会更新至系统。
                                    </p>
                                </div>
                            </template>
                            <el-image class="question-icon" src="/static/question.png"></el-image>
                        </el-tooltip>
                    </el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="上传文件" prop="code">
                <upload-file
                    v-model="importOrdersForm.code"
                    :disabled="!importOrdersForm.shop_id"
                    :source="shopSource"
                    @change="changeFile" />
            </el-form-item>
            <el-form-item v-if="importOrdersForm.code" label="">
                <div>
                    识别到 <span style="color: #ff6b00">{{ excelNum }}</span> 条数据
                </div>
            </el-form-item>
        </el-form>
        <h4 style="font-weight: 600; margin-bottom: 8px">功能说明：</h4>
        <h5 v-for="item in instructions" :key="item.id" style="line-height: 2; margin-bottom: 10px; font-size: 12px">
            {{ item.text }}
        </h5>
    </Dialog>
    <!--详情-->
    <tradingDetail ref="tradingDetailRef"></tradingDetail>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'TRADING_ORDER_MANAGE' });
</script>

<script setup lang="tsx">
import { reactive, ref, onMounted, computed, nextTick } from 'vue';
import { ElMessage, ElButton, ElPopper } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import Dialog from '@/components/Dialog.vue';
import { getDictEnum } from '@/api/ecommerce/storeManage';
import {
    getOrderList,
    exportOrders,
    importOrders,
    getOrderSourceList,
    getOrderStoreList,
    synchronous,
    synchronousPro,
    getExcelNum,
    getExcelResult,
    getOrderState
} from '@/api/ecommerce/tradingManage';
import ZWSearch from '@/components/zw/search-form/SearchForm';
import ZWTable from '@/components/zw/table/Table';
import uploadFile from '../../components/uploadFile.vue';
import selectStore from '../../components/selectStore.vue';
import tradingDetail from '../../components/tradingDetail.vue';
import tableHeaderTooltip from '../../components/tableHeaderTooltip.vue';

import lodash from 'lodash';
import { downloadFile, getSetionId } from '@/utils/utils';
import router from '@/router';

const orderTableRef = ref<HTMLElement | null>(null);
const synchronousProFormRef = ref<FormInstance>();
const importOrdersFormRef = ref<FormInstance>();
const tradingDetailRef = ref<FormInstance>();
const tips = ref<string>('订单编号相同时，请选择以下处理方式：');
const synchronousOrderTips = ref<string>(
    '同一店铺类型、店铺名称下，订单编号作为唯一标识，相同订单编号的数据将会跳过不处理'
);
const synchronousTips = ref<any[]>([
    {
        id: 1,
        text: '直接同步：'
    },
    {
        id: 2,
        text: '淘宝/天猫店铺：同步最近90天的订单。'
    },
    {
        id: 3,
        text: '有赞店铺：同步最近90天的订单。'
    },
    {
        id: 4,
        text: '抖店店铺：同步最近90天以内（不包括90天）的订单。'
    },
    {
        id: 5,
        text: '快手店铺：同步最近90天的订单。'
    },
    {
        id: 6,
        text: '客易达店铺：同步最近180天的订单。'
    },
    {
        id: 7,
        text: '其他店铺：同步最近90天的订单。'
    }
]);
const synchronousProTips = ref<string>('同步选择指定店铺指定时间段的数据');

const order_num_tips = ref<any[]>([
    {
        id: 1,
        text: '购买平台中订单的唯一编号'
    }
]);
const account_tips = ref<any[]>([
    {
        id: 1,
        text: '购买平台中客户的唯一标识'
    }
]);
const cust_tips = ref<any[]>([
    {
        id: 1,
        text: '绑定客易达客户信息'
    },
    {
        id: 2,
        text: '1. 客易达、自营、有赞、视频号小店订单：通过订单下单人ID关联系统中的客户。'
    },
    {
        id: 3,
        text: '2. 京东、抖店、快手小店订单：通过订单收件人手机号关联系统中的客户。'
    },
    {
        id: 4,
        text: '3. 淘宝、天猫订单：通过订单收件人手机号/虚拟号服务关联系统中的客户。'
    }
]);

const updateTime = ref<string>('');
const excelNum = ref<number>(0);

const pickDay = ref<any>(null);
const impose = ref<number>(90);
const isAbortNow = ref<boolean>(false);
const isShowRefresh = ref<boolean>(false);
const isShowRefreshExport = ref<boolean>(false);
const douTips = ref<boolean>(false);
const jobId = ref<any>('');
const shopSource = ref<any>('');

const instructions = ref<any>([
    {
        id: 1,
        text: '1.支持导入淘宝、天猫、抖店平台的订单数据。'
    },
    {
        id: 2,
        text: '2.导入订单的收货人信息支持明文、密文。'
    },
    {
        id: 3,
        text: '3.明文订单不会占用解析额度，密文订单将会按照对应店铺解析规则实时/定时导入系统。'
    }
]);
const orderStoreTypes = reactive<any>([]);
// 高级同步
type synchronousProFormType = {
    shop_id?: string[];
    order_time: string[];
    method: number | string;
};
const synchronousProForm = reactive<synchronousProFormType>({
    shop_id: [],
    order_time: [],
    method: 1
});
const synchronousProFormRules = reactive<FormRules>({
    shop_id: [{ required: true, message: '请选择归属店铺', trigger: 'blur' }],
    order_time: [{ required: true, message: '请选择下单时间', trigger: 'change' }]
});

// 导入订单
type importOrdersFormType = {
    shop_id?: string | number;
    method: number | string;
    code: string;
};
const importOrdersForm = reactive<importOrdersFormType>({
    shop_id: '',
    method: 1,
    code: ''
});
const importOrdersFormRules = reactive<FormRules>({
    shop_id: [{ required: true, message: '请选择店铺', trigger: 'change' }],
    code: [{ required: true, message: '请上传文件', trigger: 'change' }]
});

const fileInfo = ref<any>({
    type: 5,
    label: '文件',
    prop: 'files',
    multiple: false,
    limitSize: 20,
    limitNum: 1,
    acceptFile: '.xls,.xlsx',
    files: []
});

type defaultParamsType = {
    source: number | string;
    external_order_id: string;
    state: number | string;
    actually_amount: any[];
    cust_nameormobile: string;
    type: number | string;
    shop_idorname: string;
    store_id: number | string;
    belong_staff: number | string;
    order_time: string[];
    updated_at: string[];
};
const defaultParams: defaultParamsType = {
    source: 0, // 0-全部 1-客易达  2-有赞 3-淘宝 4-自营 5-线下门店
    external_order_id: '',
    state: 0,
    actually_amount: [],
    cust_nameormobile: '',
    type: 0,
    shop_idorname: '',
    store_id: 0,
    belong_staff: 0,
    order_time: [],
    updated_at: []
};

type stateType = {
    searchParams: defaultParamsType;
    inputParams: defaultParamsType;
    deleteId: number | string;
};
const state = reactive<stateType>({
    searchParams: lodash.cloneDeep(defaultParams),
    inputParams: lodash.cloneDeep(defaultParams),
    deleteId: ''
});
const decryptStates: {
    id: number;
    name: string;
}[] = [
    {
        id: -1,
        name: '全部'
    },
    {
        id: 1,
        name: '已解析'
    },
    {
        id: 2,
        name: '未解析'
    }
];
const relationStates: {
    id: number;
    name: string;
}[] = [
    {
        id: -1,
        name: '全部'
    },
    {
        id: 1,
        name: '已关联客户'
    },
    {
        id: 2,
        name: '未关联客户'
    }
];
const searchOption = computed(() => {
    return [
        {
            label: '订单来源',
            name: 'source',
            value: '',
            type: 'select',
            placeholder: '请选择订单来源',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    const params = { dict_id: 2 };
                    getOrderSourceList(params).then((res: any) => {
                        const targetArr: any = [];
                        res.forEach((item: any) => {
                            targetArr.push(item);
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '订单编号',
            name: 'external_order_id',
            value: '',
            type: 'input',
            placeholder: '请输入订单编号搜索'
        },
        {
            label: '订单状态',
            name: 'state',
            value: '',
            type: 'select',
            placeholder: '请选择订单状态',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getOrderState().then((res: any) => {
                        const targetArr: any = [];
                        res[0].state_list.map((item: any) => {
                            const obj = {
                                name: item.name,
                                id: item.value
                            };
                            targetArr.push(obj);
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any): any => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '实付金额',
            name: 'actually_amount',
            value: [],
            type: 'section',
            placeholder: '请输入订单编号搜索'
        },
        {
            label: '订单解析',
            name: 'is_decode',
            value: '',
            type: 'select',
            placeholder: '请选择解析结果',
            optionList: decryptStates,
            formatOption: (v: any): any => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '购买客户',
            name: 'cust_nameormobile',
            value: '',
            type: 'input',
            placeholder: '请输入客户姓名｜手机号搜索'
        },
        {
            label: '关联客户',
            name: 'is_related_cust',
            value: '',
            type: 'select',
            placeholder: '请选择关联状态',
            optionList: relationStates,
            formatOption: (v: any): any => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '店铺类型',
            name: 'type',
            value: '',
            type: 'select',
            placeholder: '请选择店铺类型',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    const params = { dict_id: 1 };
                    getDictEnum(params).then((res: any) => {
                        const targetArr: any = [];
                        res.forEach((item: any) => {
                            targetArr.push(item);
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '归属店铺',
            name: 'shop_idorname',
            value: '',
            type: 'input',
            placeholder: '请输入店铺ID｜名称搜索'
        },

        {
            label: '关联门店',
            name: 'store_id',
            value: '',
            type: 'select',
            placeholder: '全部',
            popperClass: 'zw-hide_select_option',
            isShopSelect: true,
            formatOption: (v: any) => ({
                label: v.store_name,
                value: v.id
            })
        },

        {
            label: '归属员工',
            name: 'belong_staff',
            value: '',
            type: 'select',
            placeholder: '全部',
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },

        {
            label: '下单时间',
            name: 'order_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '更新时间',
            name: 'updated_at',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        }
    ];
});

const tableOption = [
    {
        prop: 'external_order_id',
        label: '订单编号',
        width: 180,
        renderHeader({ row, index }: any) {
            return <tableHeaderTooltip title="订单编号" content={order_num_tips.value} />;
        }
    },
    {
        prop: 'source',
        label: '订单来源',
        width: 160,
        render({ row }: any) {
            return row?.source ? row?.source : '--';
        }
    },
    {
        prop: 'state',
        label: '订单状态',
        width: 160,
        renderHeader({ row, index }: any) {
            return <tableHeaderPopover title="订单状态" />;
        }
    },
    {
        prop: 'buy_user_name',
        label: '购买账号',
        width: 180,
        showOverflowTooltip: true,
        renderHeader({ row, index }: any) {
            return <tableHeaderTooltip title="购买账号" content={account_tips.value} />;
        }
    },
    {
        prop: 'bind_cust_name',
        label: '绑定客户',
        width: 220,
        render({ row }: any) {
            const { bind_cust_name, bind_cust_mobile, bind_cust_id: id = 0, type: type = 1 } = row;
            if (!!bind_cust_name || !!bind_cust_mobile) {
                return (
                    <div
                        style="display: flex;align-items: center;cursor:pointer;color:#606266;"
                        onClick={() => {
                            const url = `/customer/manage/list/detail?id=${id}&type=${type}`;
                            window.open(url, '_blank');
                        }}>
                        <span>
                            {`${bind_cust_name || ''}`}
                            {bind_cust_mobile ? `(${bind_cust_mobile || ''})` : ''}
                        </span>
                    </div>
                );
            } else {
                return '--';
            }
        },
        renderHeader({ row, index }: any) {
            return <tableHeaderTooltip title="绑定客户" content={cust_tips.value} />;
        }
    },
    {
        prop: 'cope_amount',
        label: '实付/应付金额（元）',
        width: 200,
        render({ row }: any) {
            const { cope_amount, actually_amount } = row;
            return `${actually_amount || '--'}/${cope_amount || '--'}元`;
        }
    },
    {
        prop: 'refund_amount',
        label: '退款金额',
        width: 200,
        render({ row }: any) {
            const { refund_amount } = row;
            return `${refund_amount}元`;
        }
    },
    {
        prop: 'remark',
        label: '订单备注',
        width: 200,
        render({ row }: any) {
            const { remark } = row;
            return `${remark || '--'}`;
        }
    },
    {
        prop: 'retail_shop_name',
        label: '归属店铺',
        width: 220,
        render({ row }: any) {
            return row?.retail_shop_name ? row?.retail_shop_name : '--';
        }
    },
    {
        prop: 'store_code_name',
        label: '关联门店',
        width: 220,
        render({ row }: any) {
            return row?.store_code_name ? row?.store_code_name : '--';
        }
    },
    {
        prop: 'belong_staff',
        label: '归属员工',
        width: 180,
        render({ row }: any) {
            return row?.belong_staff ? row?.belong_staff : '--';
        }
    },
    {
        prop: 'order_time',
        label: '下单时间',
        minWidth: 200
    },
    {
        prop: 'updated_at',
        label: '更新时间',
        minWidth: 200,
        render({ row }: any) {
            return row?.updated_at ? row?.updated_at : '--';
        }
    },
    {
        prop: 'operate',
        label: '操作',
        width: 110,
        align: 'center',
        fixed: 'right',
        isOperate: true,
        option({ row }) {
            if (['快手小店', '视频号小店', '抖店', '淘宝', '天猫'].includes(row.source)) {
                return [
                    {
                        name: '详情',
                        click: (row: any) => {
                            handleDetail(row);
                        }
                    }
                ];
            }
        }
    }
];

const expandSearch = () => {
    nextTick(() => {
        orderTableRef.value.getTableH();
    });
};
//切换店铺
const changeShop = (val: any) => {
    orderStoreTypes.forEach((item: any) => {
        if (item.id == val) {
            shopSource.value = item.source;
        }
    });
};
//详情
const handleDetail = (val: any) => {
    tradingDetailRef.value.openDetail(val);
};
// 高级同步
const cancelHandelSynchronousPro = (): void => {
    appDialogSynchronousPro.visible = false;
};
const submitHandelSynchronousPro = async () => {
    if (!synchronousProFormRef.value) return;
    await synchronousProFormRef.value.validate(async (valid: any): Promise<void> => {
        if (valid) {
            const end = synchronousProForm.order_time[1];
            const endTime = end.replace(/00:00:00/, '23:59:59');
            synchronousProForm.order_time[1] = endTime;
            const res: any = await synchronousPro(synchronousProForm);
            if (res) {
                isShowRefresh.value = true;
                ElMessage.success(res.msg);
                appDialogSynchronousPro.visible = false;
                reloadTable();
            }
        }
    });
};
const appDialogSynchronousPro = reactive<any>({
    visible: false,
    title: '高级同步',
    width: '600px',
    cancel: cancelHandelSynchronousPro,
    submit: submitHandelSynchronousPro,
    cancelText: '取消',
    submitText: '确定'
});

// 导入订单
const cancelHandel = (): void => {
    appDialogImportOrders.visible = false;
    importOrdersForm.shop_id = '';
};
const submitHandel = async () => {
    if (!importOrdersFormRef.value) return;
    await importOrdersFormRef.value.validate((valid: any): void => {
        if (valid) {
            importOrders(importOrdersForm).then((res: any) => {
                const { success_count, msg, job_id } = res;

                if (job_id) {
                    ElMessage.success('文件已上传，订单导入执行中，请刷新页面查看导入结果');
                    jobId.value = job_id;
                    isShowRefreshExport.value = true;
                    cancelHandel();
                    reloadTable();
                } else if (msg) {
                    ElMessage.error(msg);
                }
            });
        }
    });
};
const appDialogImportOrders = reactive<any>({
    visible: false,
    title: '导入订单',
    width: '600px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定'
});

const changeFile = async (code: string): Promise<void> => {
    const { total: total = 0 } = await getExcelNum({ code: code, source: shopSource.value });
    excelNum.value = total;
    importOrdersFormRef.value.clearValidate();
};

const tableDataChange = (data: any): void => {
    updateTime.value = data.last_sync_time;
};

const disabledDate = (time: number) => {
    const currentTime = new Date().getTime();
    if (time > currentTime) {
        return true;
    }
    if (!pickDay.value) {
        return false;
    }
    if (impose.value) {
        const con1 = new Date(pickDay.value).getTime() - impose.value * 24 * 60 * 60 * 1000;
        const con2 = new Date(pickDay.value).getTime() + impose.value * 24 * 60 * 60 * 1000;
        return time < con1 || time > con2;
    }
    return false;
};
const handleChange = (val: Date[]) => {
    if (impose.value) {
        const [pointDay] = val;
        pickDay.value = pointDay;
    }
};
const handleFocus = () => {
    pickDay.value = null;
};

const changeStore = (value: any) => {
    //  source  1 客易达   2 有赞   3 淘宝   4 自营   5 线下门店   6 天猫   7 抖店   8 京东
    if (value?.length) {
        const minArr = getSetionId('order_sync_limit_time', value);
        impose.value = Math.min(...minArr);
        const sourceType = getSetionId('source', value);
        douTips.value = sourceType.includes(7);
    }
    synchronousProFormRef.value.validateField('shop_id');
};

const search = (data: any): void => {
    state.searchParams = data;
};
const changeSearchForm = (data: any): void => {
    state.inputParams = data;
};
const reset = (): void => {
    orderTableRef.value.getTable().clearSelection();
    state.searchParams = lodash.cloneDeep(defaultParams);
    state.inputParams = lodash.cloneDeep(defaultParams);
};
// 刷新表格
const reloadTable = () => {
    orderTableRef.value.reload();
};
const resetExport = async () => {
    const res = await getExcelResult({ job_id: jobId.value });
    if (res) {
        const { import_success_num, import_fail_num } = res;
        ElMessage.success(`成功导入${import_success_num}条，失败${import_fail_num}条`);
        isShowRefreshExport.value = false;
    }
};
const fetchApi = (): any => {
    return new Promise((resolve: any): any => {
        const page_size: string | number = 15;
        const params = {};
        resolve([params, getOrderList]);
    });
};

const synchronousData = async () => {
    const res: any = await synchronous({});
    if (res) {
        isShowRefresh.value = true;
        ElMessage.success(res.msg);
        reloadTable();
    }
};
const synchronousProData = () => {
    appDialogSynchronousPro.visible = true;
};

const exportOrdersClick = async () => {
    const { url: url = '' } = await exportOrders(state.inputParams);
    url && downloadFile(url);
};

const importOrdersClick = () => {
    importOrdersForm.method = 1;
    importOrdersForm.code = '';
    excelNum.value = 0;
    return getOrderStoreList({}).then((res: any) => {
        orderStoreTypes.splice(0);
        orderStoreTypes.push(...res);
        if (res?.length) {
            importOrdersForm.shop_id = res[0].id;
            shopSource.value = res[0].source;
        } else {
            importOrdersForm.shop_id = '';
            shopSource.value = '';
        }
        appDialogImportOrders.visible = true;
    });
};
</script>

<style lang="scss" scoped>
.order_manage_container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

.tips {
    line-height: 2;
    font-size: 13px;
    color: #555;
    font-weight: 300;
    letter-spacing: 1px;
}

.store_state {
    display: flex;
    align-items: center;

    .state_label {
        width: 16px;
        height: 16px;
        border-radius: 50%;
        background-color: #2fb6e4;
    }

    .state_text {
        margin-left: 4px;
    }
}

.question-icon {
    width: 16px;
    height: 16px;
    vertical-align: sub;
}

.shop-icon {
    width: 20px;
    height: 20px;
    margin-right: 10px;
    border-radius: 100px;
}
</style>
